package com.yellowpage.nsp.action;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.yellowpage.nsp.data.NspFetchLog;
import com.yellowpage.nsp.data.NspLogSum;
import com.yellowpage.nsp.service.NspFetchLogService;
import com.yellowpage.nsp.service.NspGetLoggerServiceImpl;
import com.yellowpage.nsp.service.NspLogSumService;
import com.yellowpage.nsp.service.NspLogSumServiceImpl;
import com.yellowpage.nsp.service.NspServerService;
import com.yellowpage.white.common.Configuration;
import com.yellowpage.white.struts.BaseAction;
import com.yellowpage.white.util.ReadLog;

public class NspFetchLogAction extends BaseAction {

	public String RESULT_QUERY = "query";
	public String RESULT_ADD = "add";
	public String RESULT_EDIT = "edit";
	public String RESULT_FETCH_LOG = "fetchLog";
	private final static Properties properties = new Properties();

	private String put_linux_dir;
	private Configuration configuration;
	private ReadLog readlog;
	private NspLogSumService nspLogSumService;

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

	private List<NspFetchLog> nspFetchLogList = new ArrayList<NspFetchLog>();
	private List<Map> resultList = new ArrayList<Map>();

	private NspFetchLog nspFetchLog;
	private NspFetchLogService nspFetchLogService;
	private NspGetLoggerServiceImpl nspGetLoggerService;
	private NspServerService nspServerService;

	private String selectedId;
	private String[] selectedIds;
	private String message;

	private String query_fetchLogId;

	private String query_serverId;
	private String query_logFileName;

	private String query_fetchType;
	private String query_fetchTable;
	private String query_note;
	private String query_startLogId;
	private String query_endLogId;
	private String query_endTime;
	private String query_startTime;
	private String query_status;

	private String server;
	private String fileName;
	private String logerDate;
	private String startTime;
	private String endTime;

	// private List<Map<String,String>> timeQuantumList;

	public void prepare() {
		super.prepare();

		if (this.selectedId != null && !this.selectedId.equals("")) {
			this.nspFetchLog = nspFetchLogService.getNspFetchLog(Long
					.parseLong(selectedId));
		}

	}

	public String queryByPage() {
		initPageRender();

		Map queryMap = new HashMap();
		queryMap.put("serverId", query_serverId);
		queryMap.put("logFileName", query_logFileName);
		queryMap.put("fetchLogId", query_fetchLogId);
		queryMap.put("fetchType", query_fetchType);
		queryMap.put("fetchTable", query_fetchTable);
		queryMap.put("note", query_note);
		queryMap.put("startLogId", query_startLogId);
		queryMap.put("endLogId", query_endLogId);
		queryMap.put("endTime", query_endTime);
		queryMap.put("startTime", query_startTime);
		queryMap.put("status", query_status);

		resultList = nspFetchLogService.queryNspFetchLogByPage(queryMap,
				pageRender);

		setPageRenderToRequest();

		return RESULT_QUERY;
	}

	public String fetchNspLogData() {
		NspFetchLog nspFetchLog = new NspFetchLog();

		nspFetchLog.setFetchType("NSP_LOG");
		nspFetchLog.setFetchTable("logger,tellog");
		nspFetchLog.setStartTime(new Date());

		nspFetchLogService.saveNspFetchLog(nspFetchLog);

		nspFetchLogService.fetchNspLogData(nspFetchLog);

		message = "数据获取启动成功!";

		return RESULT_FETCH_LOG;
	}

	public String toAdd() {
		return RESULT_ADD;
	}

	public String save() {

		nspFetchLogService.saveNspFetchLog(nspFetchLog);

		message = "新增成功!";
		return RESULT_ADD;
	}

	public void validateSave() {
		if (nspFetchLog.getFetchType().length() == 0) {
			this.addActionError("** FetchType 不能为空 !");
		}
		if (nspFetchLog.getFetchTable().length() == 0) {
			this.addActionError("** FetchTable 不能为空 !");
		}
		if (nspFetchLog.getNote().length() == 0) {
			this.addActionError("** Note 不能为空 !");
		}
		if (nspFetchLog.getStatus().length() == 0) {
			this.addActionError("** Status 不能为空 !");
		}

		this.setValidatorResult("/nsp/NspFetchLogAdd.jsp");
	}

	public String toEdit() {
		Long id = new Long(selectedId);

		nspFetchLog = nspFetchLogService.getNspFetchLog(id);

		return RESULT_EDIT;
	}

	public String update() {

		nspFetchLogService.updateNspFetchLog(nspFetchLog);

		message = "修改成功!";

		return RESULT_EDIT;
	}

	public void validateUpdate() {
		if (nspFetchLog.getFetchType().length() == 0) {
			this.addActionError("** FetchType 不能为空 !");
		}
		if (nspFetchLog.getFetchTable().length() == 0) {
			this.addActionError("** FetchTable 不能为空 !");
		}
		if (nspFetchLog.getNote().length() == 0) {
			this.addActionError("** Note 不能为空 !");
		}
		if (nspFetchLog.getStatus().length() == 0) {
			this.addActionError("** Status 不能为空 !");
		}
		this.setValidatorResult("/nsp/NspFetchLogUpdate.jsp");
	}

	public String delete() {
		List ids = new ArrayList();

		for (String id : selectedIds) {
			ids.add(Long.valueOf(id));
		}

		try {
			this.nspFetchLogService.delete(ids);
		} catch (Exception e) {
			System.out.println("异常....");
			this.addActionError("** 可能含有子记录约束冲�?删除失败 !");
		}

		return queryByPage();
	}

	public String getServerLoger() {
		String zipPath = "";
		String logPath = "";
		
		try {
			properties.load(this.getClass().getClassLoader()
					.getResourceAsStream("constants.properties"));

		} catch (Exception e) {
			e.printStackTrace();
		}

		if (server != null) {
			List<Map> serviceList = nspServerService.getServer(server);
			for (Map map : serviceList) {
				String serverName = map.get("IP").toString();
				String serverLoginName = map.get("USER_NAME").toString();
				String serverLoginPwd = map.get("USER_PASSWORD").toString();
				String logDir = map.get("LOG_DIR").toString();

				String serverNum = properties.getProperty("LOGERSERVERONENUM") != null ? properties
						.getProperty("LOGERSERVERONENUM") : "";
				String put_linux_dir = properties.getProperty("LOGERSAVURL") != null ? properties
						.getProperty("LOGERSAVURL") : "";

				Integer lastStartTime = Integer.parseInt(endTime);
				Integer lastEndTime = Integer.parseInt(startTime);
				if (lastStartTime > lastEndTime) {
					for (int i = 0; i <= lastEndTime - lastStartTime; i++) {
						String dateTime = "";
						if ((lastEndTime + i) < 10) {
							dateTime = logerDate + "-0" + (lastEndTime + i);
						} else {
							dateTime = logerDate + "-" + (lastEndTime + i);
						}
						try {
							
							// logPath="E:/object/fatal_2014-12-03-13.log";
							// String fileName="fatal_"+dateTime+".log.zip";
							String fileName = dateTime + ".zip";

							zipPath = put_linux_dir + logDir + '/'
									+ fileName;

							System.out
									.println("^^^^^^^^^^^^^^^^^^^^ getServerLoger zipPath:"
											+ zipPath);

						

							logPath = NspGetLoggerServiceImpl
									.unZip(zipPath);

							System.out
									.println("^^^^^^^^^^^^^^^^^^^^ getServerLoger logPath:"
											+ logPath);
							
						} catch (Exception e) {
							message = "没有这个时间段的日志";
							e.printStackTrace();
						}

					}
				} else {
					// String dateTime=logerDate+"-"+startTime;
					// String
					// fileName="fatal_"+logerDate+"-"+startTime+".log.zip";
					String fileName = logerDate + "-" + startTime + ".zip";
					try {
						
						zipPath = put_linux_dir + logDir + "/"
								+ fileName;

						System.out
								.println("^^^^^^^^^^^^^^^^^^^^ getServerLoger 2 zipPath:"
										+ zipPath);

						logPath = NspGetLoggerServiceImpl.unZip(zipPath);

						System.out
								.println("^^^^^^^^^^^^^^^^^^^^ getServerLoger 2 logPath:"
										+ logPath);
						
					} catch (Exception e) {
						message = "没有这个时间段的日志";
						e.printStackTrace();
					}

				}
					
				if (!logPath.equals("")) {


					System.out.println("^^^^^^^^^^^^^^^^^^^^ savLogSum :" + logPath + " : "
							+ serverNum);
					
					

					
						Integer userId = Integer.parseInt(loginUser.getUserId().toString());
						try {
							List<Map> list = readlog.BufferedReader(logPath);
							if (list.size() > 0) {

								for (Map sumMap : list) {

									NspLogSum logsum = new NspLogSum();
									logsum.setServerId(Integer.parseInt(serverNum));
									logsum.setLogFileName(sumMap.get("logFileName").toString());
									logsum.setLogTime(sumMap.get("logTime").toString());
									logsum.setRequestType(sumMap.get("requestType").toString());
									logsum.setResponseCode(sumMap.get("responseCode")
											.toString());
									logsum.setCount(Integer.parseInt(sumMap.get("count")
											.toString()));
									logsum.setStatus("1");
									logsum.setCreateUser(userId);
									logsum.setCreateTime(new Date());
									nspLogSumService.saveNspLogSum(logsum);
								}
							}
							
						} catch (IOException e) {
							e.printStackTrace();
						} catch (ParseException e) {
							e.printStackTrace();
						}

				

					
				} else {
					message = "没有这个时间段的日志";
				}				
			}
		} else {
			message = "没有日志";
		}

		return RESULT_QUERY;
	}


	/**
	 * getters and setters
	 * 
	 * @return
	 */
	public void setNspFetchLog(NspFetchLog nspFetchLog) {
		this.nspFetchLog = nspFetchLog;
	}

	public NspFetchLog getNspFetchLog() {
		return nspFetchLog;
	}

	public void setNspFetchLogService(NspFetchLogService nspFetchLogService) {
		this.nspFetchLogService = nspFetchLogService;
	}

	public List<NspFetchLog> getNspFetchLogList() {
		return nspFetchLogList;
	}

	public void setNspFetchLogList(List<NspFetchLog> nspFetchLogList) {
		this.nspFetchLogList = nspFetchLogList;
	}

	public String getSelectedId() {
		return selectedId;
	}

	public void setSelectedId(String selectedId) {
		this.selectedId = selectedId;
	}

	public String[] getSelectedIds() {
		return selectedIds;
	}

	public void setSelectedIds(String[] selectedIds) {
		this.selectedIds = selectedIds;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public List<Map> getResultList() {
		return resultList;
	}

	public void setResultList(List<Map> resultList) {
		this.resultList = resultList;
	}

	public String getQuery_fetchLogId() {
		return this.query_fetchLogId;
	}

	public void setQuery_fetchLogId(String fetchLogId) {
		this.query_fetchLogId = fetchLogId;
	}

	public String getQuery_fetchType() {
		return this.query_fetchType;
	}

	public void setQuery_fetchType(String fetchType) {
		this.query_fetchType = fetchType;
	}

	public String getQuery_fetchTable() {
		return this.query_fetchTable;
	}

	public void setQuery_fetchTable(String fetchTable) {
		this.query_fetchTable = fetchTable;
	}

	public String getQuery_note() {
		return this.query_note;
	}

	public void setQuery_note(String note) {
		this.query_note = note;
	}

	public String getQuery_startLogId() {
		return this.query_startLogId;
	}

	public void setQuery_startLogId(String startLogId) {
		this.query_startLogId = startLogId;
	}

	public String getQuery_endLogId() {
		return this.query_endLogId;
	}

	public void setQuery_endLogId(String endLogId) {
		this.query_endLogId = endLogId;
	}

	public String getQuery_endTime() {
		return this.query_endTime;
	}

	public void setQuery_endTime(String endTime) {
		this.query_endTime = endTime;
	}

	public String getQuery_startTime() {
		return this.query_startTime;
	}

	public void setQuery_startTime(String startTime) {
		this.query_startTime = startTime;
	}

	public String getQuery_status() {
		return this.query_status;
	}

	public void setQuery_status(String status) {
		this.query_status = status;
	}

	public String getServer() {
		return server;
	}

	public void setServer(String server) {
		this.server = server;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getLogerDate() {
		return logerDate;
	}

	public void setLogerDate(String logerDate) {
		this.logerDate = logerDate;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public NspLogSumService getNspLogSumService() {
		return nspLogSumService;
	}

	public void setNspLogSumService(NspLogSumService nspLogSumService) {
		this.nspLogSumService = nspLogSumService;
	}

	public NspServerService getNspServerService() {
		return nspServerService;
	}

	public void setNspServerService(NspServerService nspServerService) {
		this.nspServerService = nspServerService;
	}

}
